<template>
  <div class="audit-clause-container">
    <div class="header">
      <div class="header-content d-flex justify-content-between align-items-center">
        <h2>客户审核 - 条款审核</h2>
<!--        <button @click="goBack" class="btn btn-secondary">-->
<!--          <i class="fa fa-arrow-left mr-2"></i>返回-->
<!--        </button>-->
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-indicator">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 错误消息 -->
    <div v-if="errorMessage" class="error-message">
      <i class="fa fa-exclamation-circle mr-2"></i>{{ errorMessage }}
    </div>

    <!-- 条款审核表单 -->
    <div v-if="!loading && clause" class="card mt-4">
      <div class="card-header bg-primary text-white">
        <h3>条款审核</h3>
      </div>
      <div class="card-body">
        <div class="row">
          <div class="col-md-12">
            <div class="form-group mb-4">
              <label for="clauseContent" class="form-label">条款内容</label>
              <textarea
                  id="clauseContent"
                  class="form-control"
                  rows="5"
                  readonly
                  v-model="clause.content"
              ></textarea>
            </div>

            <div class="form-group mb-4">
              <label class="form-label">审核状态</label>
              <div class="form-check form-check-inline">
                <input
                    class="form-check-input"
                    type="radio"
                    id="approved"
                    value="APPROVED"
                    v-model="auditStatus"
                >
                <label class="form-check-label" for="approved">通过</label>
              </div>
              <div class="form-check form-check-inline">
                <input
                    class="form-check-input"
                    type="radio"
                    id="rejected"
                    value="REJECTED"
                    v-model="auditStatus"
                >
                <label class="form-check-label" for="rejected">拒绝</label>
              </div>
            </div>

            <div class="form-group mb-4">
              <label for="opinion" class="form-label">审核意见</label>
              <textarea
                  id="opinion"
                  class="form-control"
                  rows="3"
                  v-model="opinion"
                  placeholder="请输入审核意见..."
              ></textarea>
            </div>

            <div class="d-flex justify-content-end">
              <button
                  @click="submitAudit"
                  class="btn btn-primary mr-2"
                  :disabled="!auditStatus"
              >
                <i class="fa fa-save mr-2"></i>提交审核
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'

export default {
  name: 'CustomerAuditClause',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const store = useStore()

    const contractId = route.params.contractId
    const clauseId = route.params.clauseId
    const loading = ref(true)
    const errorMessage = ref('')
    const clause = ref(null)
    const auditStatus = ref('')
    const opinion = ref('')

    // 返回上一页
    const goBack = () => {
      router.push(`/customer/audit-contract/${contractId}`)
    }

    // 获取条款详情
    const fetchClause = () => {
      loading.value = true
      errorMessage.value = ''

      axios.get(`/auth/contracts/${contractId}/clauses/${clauseId}/customer-audit`, {
        headers: {
          'X-Customer-Id': store.state.user?.id
        }
      })
          .then(response => {
            clause.value = response.data
            auditStatus.value = clause.value.auditStatus === 'PENDING' ? '' : clause.value.auditStatus
          })
          .catch(error => {
            console.error('获取条款详情失败', error)
            if (error.response) {
              switch (error.response.status) {
                case 403:
                  errorMessage.value = '您没有权限审核此条款'
                  break
                case 404:
                  errorMessage.value = '条款不存在'
                  break
                default:
                  errorMessage.value = '获取条款详情失败，请稍后再试'
              }
            } else {
              errorMessage.value = '网络错误，无法获取条款详情'
            }
          })
          .finally(() => {
            loading.value = false
          })
    }

    // 提交审核（修改为POST请求）
    const submitAudit = () => {
      if (!contractId || !clauseId) {
        errorMessage.value = '提交失败：缺少必要参数'
        return
      }

      if (!auditStatus.value) {
        errorMessage.value = '请选择审核状态'
        return
      }

      if (auditStatus.value === 'REJECTED' && !opinion.value) {
        errorMessage.value = '拒绝时请提供审核意见'
        return
      }

      loading.value = true
      axios.post(`/auth/contracts/${contractId}/clauses/${clauseId}/customer-audit`, {
        auditStatus: auditStatus.value,
        opinion: opinion.value,
        type: 'customer' // 明确审核类型为客户审核
      }, {
        headers: {
          'X-Customer-Id': store.state.user?.id
        }
      })
          .then(() => {
            alert('审核已提交')
            router.push(`/customer/audit-contract/${contractId}`)
          })
          .catch(error => {
            console.error('提交审核失败', error)
            errorMessage.value = error.response?.data?.message || '提交审核失败，请稍后再试'
          })
          .finally(() => {
            loading.value = false
          })
    }

    onMounted(() => {
      fetchClause()
    })

    return {
      contractId,
      clauseId,
      loading,
      errorMessage,
      clause,
      auditStatus,
      opinion,
      goBack,
      submitAudit
    }
  }
}
</script>

<style scoped>
.audit-clause-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  min-height: 300px;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: #007bff;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.error-message {
  color: #721c24;
  background-color: #f8d7da;
  border-left: 4px solid #f5c6cb;
  padding: 12px 15px;
  border-radius: 0 4px 4px 0;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

/* 新增样式保持与其他表单一致 */
.card {
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.card-header {
  padding: 10px 15px;
  border-bottom: 1px solid #ddd;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
}

.card-body {
  padding: 15px;
}

.form-group {
  margin-bottom: 15px;
}

.form-label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-control {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.form-check {
  display: inline-block;
  margin-right: 15px;
}

.form-check-input {
  margin-right: 5px;
}

.btn {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-weight: bold;
  border: none;
}

.btn-primary {
  background-color: #42b983;
  color: white;
}

.btn-primary:hover {
  background-color: #369c6b;
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background-color: #5a6268;
}
</style>